package com.binarycube.webserver;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import com.binarycube.webserver.authenticator.IAuthenticator;
import com.binarycube.webserver.config.ServerConfig;
import com.binarycube.webserver.session.ISessionManager;
import com.binarycube.webserver.session.Session;
import com.binarycube.webserver.wrappers.WrappedRequest;
import com.binarycube.webserver.wrappers.WrappedResponse;

public class LoginHandler extends AbstractHandler {

	static Logger log = Logger.getLogger(LoginHandler.class.getName());
	
	IAuthenticator authenticator;
	ServerConfig serverConfig;
	
	public LoginHandler(ServerConfig config){
		authenticator = config.getAuthenticator();
		serverConfig = config;
	}
	



	
	@Override
	public void handle(String target, final Request baseRequest,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
	    try {
        		    	
	    	//Server wide response settings
	  	  
		     response.setCharacterEncoding("UTF-8");
		     //Wrap the request for processing
		     WrappedRequest wrappedRequest = new WrappedRequest(request);
		     WrappedResponse wrappedResponse = new WrappedResponse(response);
		     
		    
		     ISessionManager sm = serverConfig.getSessionManager();
		     Session session = sm.getSession(wrappedRequest);
		     if (session == null) session = sm.createSession(wrappedRequest);
		     if (!session.isAuthenicated()) {
		    	 if (authenticator.authenticate(wrappedRequest)) {
		    		 session.setAuthenticated();
		    		 session.setUID(authenticator.getUID(wrappedRequest));
		    	 }
		     }
		     sm.persistSession(wrappedResponse, session);
		     String redirectURL = (String)session.getProperty(Session.REDIRECT);
		     if (session.isAuthenicated()) {
		    	 //Success
		    	 if (redirectURL == null)  redirectURL = "/";
		    	 response.sendRedirect(redirectURL);
		    	 response.flushBuffer();
	             baseRequest.setHandled(true);
			    
		     } else {
		    	 //Login failed
		    	 if (redirectURL != null) {
		    		 response.sendError(HttpStatus.UNAUTHORIZED_401, "You are unauthorized to access: " + redirectURL);
			     } else {
			    	 response.sendError(HttpStatus.UNAUTHORIZED_401, "Login failed.");
			     }
 		 		baseRequest.setHandled(true);
 		 		return;
		     }
		     
        	
       		
        } catch (Exception e) {
        	log.error("Error handling page request: ", e);
        	response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Oops, there has been a problem in the server:" + e.getLocalizedMessage());
        } 
		
		
	}
	

	

}

